import time
from datetime import datetime
from socket import socket, AF_INET, SOCK_DGRAM

server_ip_port = ('127.0.0.1', 9001)
buffer_size = 1024

udp_server = socket(AF_INET, SOCK_DGRAM)  # 数据报
udp_server.bind(server_ip_port)

user_list = {}
print('服务器正常开启---')
while True:
    data,addr = udp_server.recvfrom(buffer_size)
    # print(addr, type(addr))
    if len(data) > 0:
        # print(data)
        data = eval(data.decode('utf-8'))
        if data.get('code'):
            print(data.get('code')+'连接成功！地址:{}'.format(addr))
            user_list[data.get('code')] = addr
        else:
            # pass
            # print('进行信息转发')
            # print('消息内容：', data)
            recv_code = data.get('recv_code')
            try:
                ip_port = user_list[recv_code]
                # print('信息接收人:%s,地址%s,内容:%s'%(recv_code, ip_port, data))
                udp_server.sendto(str(data).encode('utf-8'), ip_port)
            except:
                time.sleep(0.5)
                # print('该用户{}不存在！'.format(recv_code))
                resp = {"send_code": "server", "msg": "用户不在线!", "date": str(datetime.now())}
                udp_server.sendto(str(resp).encode('utf-8'), addr)